package com.sykj.fileupload.controller;

import com.baidu.ueditor.ActionEnter;
import com.sykj.fileupload.config.Response;
import com.sykj.fileupload.util.JsonUtils;
import com.sykj.fileupload.util.RandomCodeUtil;
import com.sykj.fileupload.util.Word2Html;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import java.io.*;
import java.net.HttpURLConnection;
import java.util.*;
import java.net.URL;

@Controller
public class UEditorController {
    @Value(value = "${ueditor.uploadUrl}")
    private String uploadUrl;

    @Value(value="${ueditor.rootPath}")
    private String rootPath;


    @Value("http://${server.address}:${server.port}/files/")
    private String serverPath ;


    @RequestMapping(value = "/config",headers = "Accept=application/json")
    @ResponseBody
    public void imgUpload(HttpServletRequest request,HttpServletResponse response) {
        try {
            String exec = new ActionEnter(request, rootPath).exec();
            PrintWriter writer = response.getWriter();
            writer.write(exec);
            writer.flush();
            writer.close();
        } catch (IOException | JSONException e) {
            e.printStackTrace();
        }
    }


    @RequestMapping(value = "imgUpdate")
    public void imgUpdate(MultipartFile upfile,HttpServletResponse response) {
        JSONObject j = JsonUtils.getJsonObject();
        // 获取文件名
        String fileName = upfile.getOriginalFilename();
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        // 这里我使用随机字符串来重新命名图片
        fileName = Calendar.getInstance().getTimeInMillis() + RandomCodeUtil.makeRandom() + suffixName;
        File dest = new File(uploadUrl + fileName);
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            upfile.transferTo(dest);
            String config = serverPath + fileName;
            j.put("state", "SUCCESS");
            j.put("url", config);
            j.put("title", "");
            j.put("original", "");
//            System.out.println(j.toString());
            JsonUtils.print(j, response);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 粘贴图片
     * @param response
     * @return
     */
    @RequestMapping(value = "catchImage")
    public void catchImage(HttpServletRequest request,HttpServletResponse response) throws Exception{
        String[] source =  request.getParameterValues("source[]");
        JSONObject js = JsonUtils.getJsonObject();
        List<Map> list = new ArrayList<>();
        for (String s : source) {
            URL url = new URL(s);
            //打开链接
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            //设置请求方式为"GET"
            conn.setRequestMethod("GET");
            //超时响应时间为5秒
            conn.setConnectTimeout(5 * 1000);
            //通过输入流获取图片数据
            InputStream inStream = conn.getInputStream();
            //得到图片的二进制数据，以二进制封装得到数据，具有通用性
            byte[] data = readInputStream(inStream);
            String suffixName = s.substring(s.lastIndexOf("/")+1);
            String  fileName = suffixName;
            //new一个文件对象用来保存图片，默认保存当前工程根目录
            File imageFile = new File(uploadUrl + fileName);
            //创建输出流
            FileOutputStream outStream = new FileOutputStream(imageFile);
            //写入数据
            outStream.write(data);
            //关闭输出流
            outStream.close();
            String config = serverPath + fileName;
            JSONObject j = JsonUtils.getJsonObject();
            j.put("url",config);
            j.put("source",config);
            j.put("state","SUCCESS");
            list.add(j);
        }
        js.put("state","SUCCESS");
        js.put("list",list);
        JsonUtils.print(js, response);
    }

    /**
     * 上传word
     * @param
     * @return
     */
    @RequestMapping(value = "/uploadWord",method = RequestMethod.POST)
    public ResponseEntity<Object> uploadWord(@RequestParam("file") MultipartFile file, HttpServletRequest request){
        Map<String,Object> data = new HashMap<>();
        String fileName = file.getOriginalFilename();
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        // 这里我使用随机字符串来重新命名图片
        fileName = Calendar.getInstance().getTimeInMillis() + RandomCodeUtil.makeRandom() + suffixName;
        File dest = new File(uploadUrl + fileName);
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
            try {
                String content = Word2Html.wordToHtml(uploadUrl + fileName, uploadUrl, fileName+".html");
                String newContent = StringEscapeUtils.unescapeHtml(content); //转义字符
                data.put("content",newContent);
            }catch (TransformerException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ParserConfigurationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Response.success(data);
    }


    public static byte[] readInputStream(InputStream inStream) throws Exception{
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        //创建一个Buffer字符串
        byte[] buffer = new byte[1024];
        //每次读取的字符串长度，如果为-1，代表全部读取完毕
        int len = 0;
        //使用一个输入流从buffer里把数据读取出来
        while( (len=inStream.read(buffer)) != -1 ){
            //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
            outStream.write(buffer, 0, len);
        }
        //关闭输入流
        inStream.close();
        //把outStream里的数据写入内存
        return outStream.toByteArray();
    }
}
